package com.dsx.gyj.dao;

import com.dsx.gyj.entity.User;
import com.dsx.gyj.mysqlMain.ConnectionUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * author:xiaoxue1272
 * date:2020/5/17-16:58
 * 操作数据库类
 */
public class UserCrudRepository implements CrudRepository<User> {
    @Override
    public List<User> selectAll() {
        ResultSet rs = ConnectionUtil.getSelectMethod("select id,name,sex,age from t_user");
        List<User> list = new ArrayList<>();
        while (true){
            User user = new User();
            try {
                if (!rs.next()) break;
                user.setId(rs.getInt(1));
                user.setName(rs.getString(2));
                user.setSex(rs.getString(3));
                user.setAge(rs.getInt(4));
            } catch (SQLException e) {
                e.printStackTrace();
            }
            list.add(user);
        }
        return list;
    }

    @Override
    public int insert(User user) {
        return ConnectionUtil.getOtherMethod("insert into t_user(name,sex,age) values('"+user.getName()+"','"+user.getSex()+"','"+user.getAge()+"')");
    }

    @Override
    public int delete(Object id) {
        return ConnectionUtil.getOtherMethod("delete from t_user where id="+id);
    }

    @Override
    public int update(User user) {
        return ConnectionUtil.getOtherMethod("update t_user set name='"+user.getName()+"',sex='"+user.getSex()+"',age='"+user.getAge()+"' where id="+user.getId());
    }

    @Override
    public User selectOne(Object id) {
        ResultSet rs = ConnectionUtil.getSelectMethod("select id,name,sex,age from t_user where id=" + id);
        User user = new User();
        while (true) {
            try {
                if (!rs.next()) break;
                user.setId(rs.getInt(1));
                user.setName(rs.getString(2));
                user.setSex(rs.getString(3));
                user.setAge(rs.getInt(4));
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                return user;
            }
        }
    }
}